package logic

import (
	"context"
	"fmt"
	"wechats/model/cache"
	"wechats/model/mysql"
	"wechats/wechatrpc/internal/svc"
	"wechats/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *wechatrpc.RegisterRequest) (*wechatrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var user mysql.Register
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("账号已存在,前去注册")
	}
	register := mysql.Register{

		Nickname: in.Nickname,
		Address:  in.Address,
		Mobile:   in.Mobile,
		Password: in.Password,
	}
	mysql.DB.Debug().Create(&register)
	return &wechatrpc.RegisterResponse{
		UserId: int64(register.ID),
	}, nil
}
